package org.red.base;

import java.util.ArrayList;

import org.red.action.ActionManager;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

public class CanvasView extends View {

	private Scene _scene = null;
	
	private ArrayList<Node> nodelist = new ArrayList<Node>();
	
	private Handler handler = new Handler();
    private Runnable mainLoop = new Runnable() {
        public void run() {
			handler.postDelayed(this, Config.INTERVAL);
			CanvasView.this.invalidate();
        }
    };
    
	public CanvasView(Context context) {
		super(context);
	}

	public CanvasView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	public CanvasView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public void runWithScene(Scene _scene) {
		this._scene = _scene;
		handler.post(mainLoop);
	}
	
	public void addChild(Sprite sprite) {
		nodelist.add(sprite);
	}

	private void drawNodes(ArrayList<Node> list, Canvas canvas) {
		if(list == null) {
			return;
		}
		for(Node node : list) {
			if(node.getScheduleUpdate()) {
				node.update(Config.INTERVAL);
			}
			Bitmap bmp = node.getBitmap();
			if(bmp != null) {
				canvas.drawBitmap(node.getBitmap(), node.getMatrix(), null);
			}
			drawNodes(node.getChildren(), canvas);
		}
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		ActionManager.getInstance().update(Config.INTERVAL);
		if(_scene != null) {
			drawNodes(_scene.getChildren(), canvas);
		}
	}
	
}
